# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/4/14 11:44 PM
# @Author : 曹庭
# @File : pay.py
# @Software: PyCharm
import json

from . import api
from alipay import AliPay
from course.utils.alipayback import alipay_back
from course.utils.commons import login_required
from course.utils.xuehua_id import IdWorker
from course.utils.send_mail import sendmail
from flask import g, current_app, jsonify, request, session
from course.utils.response_code import RET
from course.models import User, Order, PanShare, Course
from course import db, constants
import datetime


@api.route("/vipalipayback", methods=["POST"])
@login_required
def vip_alipay_back():
    """
    VIP对接支付宝
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id

    request_dict = request.get_json()
    total_amount = request_dict.get("total_amount")
    subject = request_dict.get("subject")

    # 应用私钥
    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
    MIIEpQIBAAKCAQEApnLghoEchJ/srSdCvVWYPF5W1rem59h0lupfIowmpKNeLlRDZWoyA+BDNBxO9ehC5tvnkp0u4LsBFPrOZTLdcYQwAJMtOMNK3LsyY8xSuDiyf0OsjutK6E35fqaHRwX/d9pun2s641pk8ON0Yz3lRD7FhgGh2f00k3mpidweYjYk2XeCldJMMzHPPA4NZEiYdVffMIME7wN0SzOho/ploN5TO7oi2QZQvn9kcdfmuQaKRqtB8pBufZoO7aN8/m5xofZQl4w2+eTbRe5dBqPsKsFGiJwDTc1WlA2mdT4wvVX7LYv4s+A/uczZPlCChIFXU0OwZavKqyRUMK4NztN6uQIDAQABAoIBACPJCvCgDYuN/opzqGugXWyNM8pSDbZG2TohBXcd/qji3rrDLwI8xKgErS4k7+z6lHehy7W/yXZTfjYOfhVPzEA9lTxqaAyOICg4ruq54QbuWaH24MCRYbd0HDHYh7kDVxtjgOkRWsXKh20q2bkEc6gqfrkC3NNLFuSmAYc8JeQjOdOYe1aycvNfvuFMW9byJTbjxaasYtZEMr9kfrV2O9XNHMBOWdT57vqs68ByLJhksc4BARIzUzioyrhGYnIRtUW/CqExW2Aq6Q1Jap1T50fRUsSwJKp2Hr4wGBt5HGudG3Dbxmsw1d7nLCenZ4hjwuABVgKqsQPt5dcnZZWDuukCgYEA9QRMEybl/W/Ma1af5VqX2CrOA7qJwNRZTW8797AkJv/XLvuoLGeYfhl/y4pXmHX4k2nI5rq/MnqgCof0T3+6sYEZAU7eMkNmUUGk89onBJ7IP+C1qmjRICFeTamnLnFRBlGuZJdwfIVY6flOgrWxA97Dgc2+KD4y0BkMkhcI8ysCgYEArej32tzinKNxRKBwR5d7HRREqQQNzkj6AQCushfLUdnhH0hVzYn2FyqmmSJCxFAvdtT79HgXfGcM/y53kVfRYLcUUX8KmMxUAHAqTrTRakubhKOPHKKnhg7+vVmTcyYp9y9iVXJ2NhwfuH5SEPaLOYzqeElaZj0kgIxl6YOop6sCgYEA3CPfQjnp3HqNfUeYZFawJU3YSetZB4MDNZqik5mT8eJecV00rajqjynT84m5yEb+b1xVYFEbpnwcvTmH3cHSeNeYIt+8rgZ2sL09Osef1PvgydvY/WItuyOf+kFa71RqyzWqbcDPFWIuEBKqYrBieiq1GDRGDRxNRUGsVLoTlX8CgYEAqv0H1NSgqkm4sDTesEUr8udeqp8lw9DUne/B07C5Y3zJbyx70F746sYwjxe0dbgxMrEuGKuKy/G2QZ+6R9kEMAdRnt892AXuAZBGyKPX0p8MBVma+BikhZZwuFM+OlUnpbWdBU5JE+KK/aaVocAGG0uFrUbR7vvmy80+1l1wkYkCgYEA2PbGnJqgv9Q2W0GfnW65qiJOtzDDxfJnnZZXMI2AiWDzFWlN5J9A5zXtYvLkwutQm9UGOeFsmm6NlY84txokb6I5vUyIkYJxtkPYfhcKd0Uy4MY6RovRuREsPsrQLFEqVsdpnbE2YRrYP5uNBzVAXQMsxN5AZMKqfdbK1ii5Yw0=
    -----END RSA PRIVATE KEY-----"""

    # 支付宝公钥
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAghmFpme+aWIGmsWY8ASfCnuXp0n4+thAd8dfsdxawN738JpVEY/IPzWJ0HPgzByL1swLI3OKbkCNX+RjGzeLxSnMotOAOgRtEOmdR6rtg/4pA0ao7uWwwHCf9ND24NLDVFR4io8+PDTYMq88q+hBKrdt8ISGIWe60WHspcAQGA+PjHcArgQ4dJD1xYW+X87RyRz3u/xZ6ckwLuwQ/U0W6Oewete6FORo0UrqHaON+EoQRC/9XWOVWTzF8q54kLJoFtIy3hs3LFT+evAw8uq7sEKeRZF3gILxVrgOjOWnNmKN3tnINALXbDNkMxtTCvS+BX79I+GldubRIP4NYgWuzQIDAQAB
    -----END PUBLIC KEY-----"""

    # 应用ID
    app_id = "2021000119623921"
    sign_type = "RSA2"

    return_url = 'http://127.0.0.1:5000/web_payComplete.html'
    # notify_url = 'http://127.0.0.1:8000'
    notify_url = None

    # 支付宝的网关地址（支付地址域名）
    ALIPAY_URL_GATEWAY = 'https://openapi.alipaydev.com/gateway.do?'

    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=sign_type,  # RSA 或者 RSA2，不写默认是RSA2
        debug=True,  # 默认 False
    )
    # 电脑网站支付，需要跳转到：https://openapi.alipay.com/gateway.do? + order_string
    res = alipay.api_alipay_trade_page_pay(
        out_trade_no=IdWorker(1, 1, 0).get_id(),
        total_amount=float(total_amount),  # 只有生成支付宝链接时，不能用Decimal
        subject=subject,
        return_url=return_url,
        notify_url=notify_url
    )

    # print(res)
    gateway_url = ALIPAY_URL_GATEWAY + res
    print(gateway_url)

    return jsonify(code=RET.OK, errmsg="保存成功", data={'gateway_url': gateway_url})


@api.route("/payment", methods=["POST"])
@login_required
def payment():
    """
    VIP支付验证
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id

    alipay_dict = request.form.to_dict()
    # 对支付宝的数据精选分离， 提取出支付宝的签名
    alipay_sign = alipay_dict.pop("sign")

    # 应用私钥
    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
        MIIEpQIBAAKCAQEApnLghoEchJ/srSdCvVWYPF5W1rem59h0lupfIowmpKNeLlRDZWoyA+BDNBxO9ehC5tvnkp0u4LsBFPrOZTLdcYQwAJMtOMNK3LsyY8xSuDiyf0OsjutK6E35fqaHRwX/d9pun2s641pk8ON0Yz3lRD7FhgGh2f00k3mpidweYjYk2XeCldJMMzHPPA4NZEiYdVffMIME7wN0SzOho/ploN5TO7oi2QZQvn9kcdfmuQaKRqtB8pBufZoO7aN8/m5xofZQl4w2+eTbRe5dBqPsKsFGiJwDTc1WlA2mdT4wvVX7LYv4s+A/uczZPlCChIFXU0OwZavKqyRUMK4NztN6uQIDAQABAoIBACPJCvCgDYuN/opzqGugXWyNM8pSDbZG2TohBXcd/qji3rrDLwI8xKgErS4k7+z6lHehy7W/yXZTfjYOfhVPzEA9lTxqaAyOICg4ruq54QbuWaH24MCRYbd0HDHYh7kDVxtjgOkRWsXKh20q2bkEc6gqfrkC3NNLFuSmAYc8JeQjOdOYe1aycvNfvuFMW9byJTbjxaasYtZEMr9kfrV2O9XNHMBOWdT57vqs68ByLJhksc4BARIzUzioyrhGYnIRtUW/CqExW2Aq6Q1Jap1T50fRUsSwJKp2Hr4wGBt5HGudG3Dbxmsw1d7nLCenZ4hjwuABVgKqsQPt5dcnZZWDuukCgYEA9QRMEybl/W/Ma1af5VqX2CrOA7qJwNRZTW8797AkJv/XLvuoLGeYfhl/y4pXmHX4k2nI5rq/MnqgCof0T3+6sYEZAU7eMkNmUUGk89onBJ7IP+C1qmjRICFeTamnLnFRBlGuZJdwfIVY6flOgrWxA97Dgc2+KD4y0BkMkhcI8ysCgYEArej32tzinKNxRKBwR5d7HRREqQQNzkj6AQCushfLUdnhH0hVzYn2FyqmmSJCxFAvdtT79HgXfGcM/y53kVfRYLcUUX8KmMxUAHAqTrTRakubhKOPHKKnhg7+vVmTcyYp9y9iVXJ2NhwfuH5SEPaLOYzqeElaZj0kgIxl6YOop6sCgYEA3CPfQjnp3HqNfUeYZFawJU3YSetZB4MDNZqik5mT8eJecV00rajqjynT84m5yEb+b1xVYFEbpnwcvTmH3cHSeNeYIt+8rgZ2sL09Osef1PvgydvY/WItuyOf+kFa71RqyzWqbcDPFWIuEBKqYrBieiq1GDRGDRxNRUGsVLoTlX8CgYEAqv0H1NSgqkm4sDTesEUr8udeqp8lw9DUne/B07C5Y3zJbyx70F746sYwjxe0dbgxMrEuGKuKy/G2QZ+6R9kEMAdRnt892AXuAZBGyKPX0p8MBVma+BikhZZwuFM+OlUnpbWdBU5JE+KK/aaVocAGG0uFrUbR7vvmy80+1l1wkYkCgYEA2PbGnJqgv9Q2W0GfnW65qiJOtzDDxfJnnZZXMI2AiWDzFWlN5J9A5zXtYvLkwutQm9UGOeFsmm6NlY84txokb6I5vUyIkYJxtkPYfhcKd0Uy4MY6RovRuREsPsrQLFEqVsdpnbE2YRrYP5uNBzVAXQMsxN5AZMKqfdbK1ii5Yw0=
        -----END RSA PRIVATE KEY-----"""

    # 支付宝公钥
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAghmFpme+aWIGmsWY8ASfCnuXp0n4+thAd8dfsdxawN738JpVEY/IPzWJ0HPgzByL1swLI3OKbkCNX+RjGzeLxSnMotOAOgRtEOmdR6rtg/4pA0ao7uWwwHCf9ND24NLDVFR4io8+PDTYMq88q+hBKrdt8ISGIWe60WHspcAQGA+PjHcArgQ4dJD1xYW+X87RyRz3u/xZ6ckwLuwQ/U0W6Oewete6FORo0UrqHaON+EoQRC/9XWOVWTzF8q54kLJoFtIy3hs3LFT+evAw8uq7sEKeRZF3gILxVrgOjOWnNmKN3tnINALXbDNkMxtTCvS+BX79I+GldubRIP4NYgWuzQIDAQAB
        -----END PUBLIC KEY-----"""

    # 应用ID
    app_id = "2021000119623921"
    sign_type = "RSA2"

    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=sign_type,  # RSA 或者 RSA2，不写默认是RSA2
        debug=True,  # 默认 False
    )
    # 借助工具验证参数的合法性
    result = alipay.verify(alipay_dict, alipay_sign)

    if result:
        total_amount = alipay_dict.get("total_amount")
        if total_amount == '258.00':
            vip_start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            vip_end_time = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S')
        elif total_amount == '468.00':
            vip_start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            vip_end_time = "2099-1-1 00:00:00"
        try:
            User.query.filter_by(id=user_id).update(
                {"is_vip": 1, "vip_start_time": vip_start_time, "vip_end_time": vip_end_time})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库异常")

        session["is_vip"] = 1
        # 修改数据库的订单状态信息

    return jsonify(code=RET.OK, errmsg="vip开通成功")


@api.route("/orderalipayback", methods=["POST"])
@login_required
def order_alipay_back():
    """
    订单对接支付宝
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id

    request_dict = request.get_json()
    course_id = request_dict.get("course_id")
    title = request_dict.get("title")
    normal_price = request_dict.get("normal_price")

    try:
        user = User.query.filter_by(id=user_id).first()
        is_vip = user.is_vip
        mail = user.mail
        panShare = PanShare.query.filter_by(course_id=course_id).first()
        share_url = panShare.share_url
        share_code = panShare.share_code
        if is_vip == 1:
            order = Order(user_id=user_id, course_id=course_id, order_price=normal_price, order_status=2)
            try:
                db.session.add(order)
                db.session.commit()
                sendmail(title, share_url, share_code, mail)
                return jsonify(code=RET.OK, msg="已生成订单，视频资料已发送至邮箱")
            except Exception as e:
                db.session.rollback()
                current_app.logger.error(e)
                return jsonify(code=RET.DATAEXIST, msg="订单保存数据库失败")
        else:
            order = Order(user_id=user_id, course_id=course_id, order_price=normal_price, order_status=1)
            try:
                db.session.add(order)
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                current_app.logger.error(e)
                return jsonify(code=RET.DATAEXIST, msg="订单保存数据库失败")

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库异常")

    # 应用私钥
    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
    MIIEpQIBAAKCAQEApnLghoEchJ/srSdCvVWYPF5W1rem59h0lupfIowmpKNeLlRDZWoyA+BDNBxO9ehC5tvnkp0u4LsBFPrOZTLdcYQwAJMtOMNK3LsyY8xSuDiyf0OsjutK6E35fqaHRwX/d9pun2s641pk8ON0Yz3lRD7FhgGh2f00k3mpidweYjYk2XeCldJMMzHPPA4NZEiYdVffMIME7wN0SzOho/ploN5TO7oi2QZQvn9kcdfmuQaKRqtB8pBufZoO7aN8/m5xofZQl4w2+eTbRe5dBqPsKsFGiJwDTc1WlA2mdT4wvVX7LYv4s+A/uczZPlCChIFXU0OwZavKqyRUMK4NztN6uQIDAQABAoIBACPJCvCgDYuN/opzqGugXWyNM8pSDbZG2TohBXcd/qji3rrDLwI8xKgErS4k7+z6lHehy7W/yXZTfjYOfhVPzEA9lTxqaAyOICg4ruq54QbuWaH24MCRYbd0HDHYh7kDVxtjgOkRWsXKh20q2bkEc6gqfrkC3NNLFuSmAYc8JeQjOdOYe1aycvNfvuFMW9byJTbjxaasYtZEMr9kfrV2O9XNHMBOWdT57vqs68ByLJhksc4BARIzUzioyrhGYnIRtUW/CqExW2Aq6Q1Jap1T50fRUsSwJKp2Hr4wGBt5HGudG3Dbxmsw1d7nLCenZ4hjwuABVgKqsQPt5dcnZZWDuukCgYEA9QRMEybl/W/Ma1af5VqX2CrOA7qJwNRZTW8797AkJv/XLvuoLGeYfhl/y4pXmHX4k2nI5rq/MnqgCof0T3+6sYEZAU7eMkNmUUGk89onBJ7IP+C1qmjRICFeTamnLnFRBlGuZJdwfIVY6flOgrWxA97Dgc2+KD4y0BkMkhcI8ysCgYEArej32tzinKNxRKBwR5d7HRREqQQNzkj6AQCushfLUdnhH0hVzYn2FyqmmSJCxFAvdtT79HgXfGcM/y53kVfRYLcUUX8KmMxUAHAqTrTRakubhKOPHKKnhg7+vVmTcyYp9y9iVXJ2NhwfuH5SEPaLOYzqeElaZj0kgIxl6YOop6sCgYEA3CPfQjnp3HqNfUeYZFawJU3YSetZB4MDNZqik5mT8eJecV00rajqjynT84m5yEb+b1xVYFEbpnwcvTmH3cHSeNeYIt+8rgZ2sL09Osef1PvgydvY/WItuyOf+kFa71RqyzWqbcDPFWIuEBKqYrBieiq1GDRGDRxNRUGsVLoTlX8CgYEAqv0H1NSgqkm4sDTesEUr8udeqp8lw9DUne/B07C5Y3zJbyx70F746sYwjxe0dbgxMrEuGKuKy/G2QZ+6R9kEMAdRnt892AXuAZBGyKPX0p8MBVma+BikhZZwuFM+OlUnpbWdBU5JE+KK/aaVocAGG0uFrUbR7vvmy80+1l1wkYkCgYEA2PbGnJqgv9Q2W0GfnW65qiJOtzDDxfJnnZZXMI2AiWDzFWlN5J9A5zXtYvLkwutQm9UGOeFsmm6NlY84txokb6I5vUyIkYJxtkPYfhcKd0Uy4MY6RovRuREsPsrQLFEqVsdpnbE2YRrYP5uNBzVAXQMsxN5AZMKqfdbK1ii5Yw0=
    -----END RSA PRIVATE KEY-----"""

    # 支付宝公钥
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAghmFpme+aWIGmsWY8ASfCnuXp0n4+thAd8dfsdxawN738JpVEY/IPzWJ0HPgzByL1swLI3OKbkCNX+RjGzeLxSnMotOAOgRtEOmdR6rtg/4pA0ao7uWwwHCf9ND24NLDVFR4io8+PDTYMq88q+hBKrdt8ISGIWe60WHspcAQGA+PjHcArgQ4dJD1xYW+X87RyRz3u/xZ6ckwLuwQ/U0W6Oewete6FORo0UrqHaON+EoQRC/9XWOVWTzF8q54kLJoFtIy3hs3LFT+evAw8uq7sEKeRZF3gILxVrgOjOWnNmKN3tnINALXbDNkMxtTCvS+BX79I+GldubRIP4NYgWuzQIDAQAB
    -----END PUBLIC KEY-----"""

    # 应用ID
    app_id = "2021000119623921"
    sign_type = "RSA2"

    return_url = 'http://127.0.0.1:5000/web_orderPayComplete.html'
    # notify_url = 'http://127.0.0.1:8000'
    notify_url = None

    # 支付宝的网关地址（支付地址域名）
    ALIPAY_URL_GATEWAY = 'https://openapi.alipaydev.com/gateway.do?'

    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=sign_type,  # RSA 或者 RSA2，不写默认是RSA2
        debug=True,  # 默认 False
    )
    # 电脑网站支付，需要跳转到：https://openapi.alipay.com/gateway.do? + order_string
    res = alipay.api_alipay_trade_page_pay(
        out_trade_no=IdWorker(1, 1, 0).get_id(),
        total_amount=float(normal_price),  # 只有生成支付宝链接时，不能用Decimal
        subject=title,
        return_url=return_url,
        notify_url=notify_url
    )

    # print(res)
    gateway_url = ALIPAY_URL_GATEWAY + res
    print(gateway_url)

    return jsonify(code=RET.OK, errmsg="保存成功", data={'gateway_url': gateway_url})


@api.route("/orderPayment", methods=["POST"])
@login_required
def order_Payment():
    """
    订单支付验证
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id

    alipay_dict = request.form.to_dict()
    # 对支付宝的数据精选分离， 提取出支付宝的签名
    alipay_sign = alipay_dict.pop("sign")
    # trade_no = alipay_dict.pop("trade_no")
    # print(alipay_sign)
    # print(trade_no)

    # 应用私钥
    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
            MIIEpQIBAAKCAQEApnLghoEchJ/srSdCvVWYPF5W1rem59h0lupfIowmpKNeLlRDZWoyA+BDNBxO9ehC5tvnkp0u4LsBFPrOZTLdcYQwAJMtOMNK3LsyY8xSuDiyf0OsjutK6E35fqaHRwX/d9pun2s641pk8ON0Yz3lRD7FhgGh2f00k3mpidweYjYk2XeCldJMMzHPPA4NZEiYdVffMIME7wN0SzOho/ploN5TO7oi2QZQvn9kcdfmuQaKRqtB8pBufZoO7aN8/m5xofZQl4w2+eTbRe5dBqPsKsFGiJwDTc1WlA2mdT4wvVX7LYv4s+A/uczZPlCChIFXU0OwZavKqyRUMK4NztN6uQIDAQABAoIBACPJCvCgDYuN/opzqGugXWyNM8pSDbZG2TohBXcd/qji3rrDLwI8xKgErS4k7+z6lHehy7W/yXZTfjYOfhVPzEA9lTxqaAyOICg4ruq54QbuWaH24MCRYbd0HDHYh7kDVxtjgOkRWsXKh20q2bkEc6gqfrkC3NNLFuSmAYc8JeQjOdOYe1aycvNfvuFMW9byJTbjxaasYtZEMr9kfrV2O9XNHMBOWdT57vqs68ByLJhksc4BARIzUzioyrhGYnIRtUW/CqExW2Aq6Q1Jap1T50fRUsSwJKp2Hr4wGBt5HGudG3Dbxmsw1d7nLCenZ4hjwuABVgKqsQPt5dcnZZWDuukCgYEA9QRMEybl/W/Ma1af5VqX2CrOA7qJwNRZTW8797AkJv/XLvuoLGeYfhl/y4pXmHX4k2nI5rq/MnqgCof0T3+6sYEZAU7eMkNmUUGk89onBJ7IP+C1qmjRICFeTamnLnFRBlGuZJdwfIVY6flOgrWxA97Dgc2+KD4y0BkMkhcI8ysCgYEArej32tzinKNxRKBwR5d7HRREqQQNzkj6AQCushfLUdnhH0hVzYn2FyqmmSJCxFAvdtT79HgXfGcM/y53kVfRYLcUUX8KmMxUAHAqTrTRakubhKOPHKKnhg7+vVmTcyYp9y9iVXJ2NhwfuH5SEPaLOYzqeElaZj0kgIxl6YOop6sCgYEA3CPfQjnp3HqNfUeYZFawJU3YSetZB4MDNZqik5mT8eJecV00rajqjynT84m5yEb+b1xVYFEbpnwcvTmH3cHSeNeYIt+8rgZ2sL09Osef1PvgydvY/WItuyOf+kFa71RqyzWqbcDPFWIuEBKqYrBieiq1GDRGDRxNRUGsVLoTlX8CgYEAqv0H1NSgqkm4sDTesEUr8udeqp8lw9DUne/B07C5Y3zJbyx70F746sYwjxe0dbgxMrEuGKuKy/G2QZ+6R9kEMAdRnt892AXuAZBGyKPX0p8MBVma+BikhZZwuFM+OlUnpbWdBU5JE+KK/aaVocAGG0uFrUbR7vvmy80+1l1wkYkCgYEA2PbGnJqgv9Q2W0GfnW65qiJOtzDDxfJnnZZXMI2AiWDzFWlN5J9A5zXtYvLkwutQm9UGOeFsmm6NlY84txokb6I5vUyIkYJxtkPYfhcKd0Uy4MY6RovRuREsPsrQLFEqVsdpnbE2YRrYP5uNBzVAXQMsxN5AZMKqfdbK1ii5Yw0=
            -----END RSA PRIVATE KEY-----"""

    # 支付宝公钥
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
            MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAghmFpme+aWIGmsWY8ASfCnuXp0n4+thAd8dfsdxawN738JpVEY/IPzWJ0HPgzByL1swLI3OKbkCNX+RjGzeLxSnMotOAOgRtEOmdR6rtg/4pA0ao7uWwwHCf9ND24NLDVFR4io8+PDTYMq88q+hBKrdt8ISGIWe60WHspcAQGA+PjHcArgQ4dJD1xYW+X87RyRz3u/xZ6ckwLuwQ/U0W6Oewete6FORo0UrqHaON+EoQRC/9XWOVWTzF8q54kLJoFtIy3hs3LFT+evAw8uq7sEKeRZF3gILxVrgOjOWnNmKN3tnINALXbDNkMxtTCvS+BX79I+GldubRIP4NYgWuzQIDAQAB
            -----END PUBLIC KEY-----"""

    # 应用ID
    app_id = "2021000119623921"
    sign_type = "RSA2"

    alipay = AliPay(
        appid=app_id,
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=sign_type,  # RSA 或者 RSA2，不写默认是RSA2
        debug=True,  # 默认 False
    )
    # 借助工具验证参数的合法性
    result = alipay.verify(alipay_dict, alipay_sign)
    # print(result)

    if result:
        print(result)
        print(user_id)
        # return jsonify(code=RET.OK, errmsg="支付成功")
        # total_amount = alipay_dict.get("total_amount")
        trade_no = alipay_dict.get("trade_no")
        try:
            order = Order.query.filter_by(user_id=user_id).order_by("create_time").all()
            order[-1].order_status = 2
            order[-1].trade_no = trade_no
            db.session.commit()
            user = User.query.filter_by(id=user_id).first()
            mail = user.mail
            panShare = PanShare.query.filter_by(course_id=order[-1].course_id).first()
            share_url = panShare.share_url
            share_code = panShare.share_code
            course = Course.query.filter_by(id=order[-1].course_id).first()
            title = course.title
            sendmail(title, share_url, share_code, mail)
            return jsonify(code=RET.OK, errmsg="支付成功")
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库异常")

    return jsonify(code=RET.OK, errmsg="支付失败")


@api.route("/sendEmail", methods=["POST"])
@login_required
def send_email():
    user_id = g.user_id

    request_dict = request.get_json()
    course_id = request_dict.get("course_id")

    if not all([course_id]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    try:
        order = Order.query.filter_by(user_id=user_id, course_id=course_id).first()
        if order:
            course = Course.query.filter_by(id=course_id).first()
            title = course.title
            user = User.query.filter_by(id=user_id).first()
            mail = user.mail
            panShare = PanShare.query.filter_by(course_id=course_id).first()
            share_url = panShare.share_url
            share_code = panShare.share_code
            sendmail(title, share_url, share_code, mail)
        return jsonify(code=RET.OK, msg="邮件发送成功")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")
